package com.cqs.leetcode.ds.sort;

/**
 * Author:li
 * <p>
 * create date: 18-5-30 09:28
 */
public class MergeSort implements IMergeSort {


    @Override
    public void sort(int[] arr) {
        if (arr == null || arr.length <= 1) return;
        split(arr, 0, arr.length - 1);
    }

    @Override
    public void split(int[] arr, int left, int right) {
        if (left >= right) return;
        int mid = (left + right) / 2;
        split(arr, left, mid);
        split(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }

    @Override
    public void merge(int[] arr, int left, int mid, int right) {
        if (arr[mid] <= arr[mid + 1]) return;
        //复制子数组
        int llen = mid - left + 1;
        int rlen = right - mid;
        int[] lc = new int[llen];
        int[] rc = new int[rlen];
        System.arraycopy(arr, left, lc, 0, llen);
        System.arraycopy(arr, mid + 1, rc, 0, rlen);
        //注意 这里的lp rp索引从0开始
        int p = left, lp = 0, rp = 0;
        while (p <= right) {
            if (lp >= lc.length) {
                while (rp < rc.length) {
                    arr[p++] = rc[rp++];
                }
                return;
            }
            if (rp >= rc.length) {
                while (lp < lc.length) {
                    arr[p++] = lc[lp++];
                }
                return;
            }
            if (lc[lp] <= rc[rp]) {
                arr[p++] = lc[lp++];
            } else {
                arr[p++] = rc[rp++];
            }
        }
    }
}
